const app = getApp();

Page({
  data: {
    orderState: [],      // 状态列表，如 ["待处理", "进行中", "已完成"]
    orderList: [],
    total: 0,
    pageSize: 10,
    currentPage: 1,
    search: {
      userName: '',
      status: null,
      orderType: null,
    },
    orderTypes: ['普通记录', '高级记录'],
    loading: false,
    commentDialogVisible: false,
    statusHistoryDialogVisible: false,
    selectedOrder: null,
    displayedOrders: [],
    commentDialogVisible: false,
    statusHistoryDialogVisible: false,
    selectedOrder: null, // 当前选中的记录对象
    newCommentContent: '', // 新评论内容
  },

  onLoad() {
    this.fetchData();
    this.setupAutoRefresh();
  },

  onUnload() {
    if (this.refreshInterval) clearInterval(this.refreshInterval);
  },
  updateOrderStatus(e) {
    const order = e.currentTarget.dataset.order;

    wx.showModal({
      title: '提示',
      content: '确定将该记录更新到下一状态？',
      success: async (res) => {
        if (!res.confirm) return;

        const newStatus = order.currentStatus + 1;
        if (newStatus >= this.data.orderState.length) {
          wx.showToast({ title: '当前记录已失效，请先激活记录', icon: 'none' });
          return;
        }

        app.request({
          url: `/admin/order/updateOrder/${order.id}/${newStatus}`,
          method: 'PUT',
          success: (res) => {
            if (res.code === 1) {
              wx.showToast({ title: '状态更新成功' });
              this.fetchData();
            } else {
              wx.showToast({ title: res.msg || '更新失败', icon: 'none' });
            }
          },
          fail: (err) => {
            console.error(err);
            wx.showToast({ title: '更新失败', icon: 'none' });
          }
        });
      }
    });
  },

  toggleOrderValid(e) {
    const order = e.currentTarget.dataset.order;
  
    wx.showModal({
      title: '提示',
      content: order.isValid ? '确定禁用该记录？' : '确定激活该记录？',
      success: (res) => {
        if (res.confirm) {
          app.request({
            url: `/admin/order/updateOrderIsValid/${order.id}`,
            method: 'PUT',
            success: (res) => {
              if (res.code === 1) {
                wx.showToast({ title: '切换成功' });
                this.fetchData();
              } else {
                wx.showToast({ title: res.msg || '切换失败', icon: 'none' });
              }
            },
            fail: (err) => {
              console.error(err);
              wx.showToast({ title: '切换失败', icon: 'none' });
            }
          });
        }
      }
    });
  },
  deleteOrder(e) {
    const orderId = e.currentTarget.dataset.id;
  
    wx.showModal({
      title: '警告',
      content: '确定要删除该记录吗？此操作不可恢复！',
      showCancel: true,
      confirmColor: '#ff4949',
      success: async (res) => {
        if (res.confirm) {
          // 用户点击确定，开始删除
          app.request({
            url: `/admin/order/deleteOrder/${orderId}`,
            method: 'DELETE',
            success: (res) => {
              if (res.code === 1) {
                wx.showToast({ title: '删除成功' });
                this.fetchData(); // 刷新记录列表
              } else {
                wx.showToast({ title: res.msg || '删除失败', icon: 'none' });
              }
            },
            fail: (err) => {
              console.error('删除记录失败:', err);
              wx.showToast({ title: '网络错误，请重试', icon: 'none' });
            }
          });
        }
      },
      fail: () => {
        wx.showToast({ title: '操作取消', icon: 'none' });
      }
    });
  },
  downloadImages(e) {
    const orderId = e.currentTarget.dataset.id;

    wx.showLoading({
      title: '获取链接中',
      mask: true
    });

    wx.setClipboardData({
      data: `${app.globalData.apiUrl}/admin/minio/WXDownloadImage/${orderId}/${app.globalData.adminToken}`,
      success: () => {
        wx.showToast({
          title: '已复制链接到剪贴板',
          icon: 'none',
          duration: 2500
        });
      },
      fail: () => {
        wx.showToast({
          title: '复制失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  fetchData() {
    this.getOrderList();
  },
  resetSearch() {
    this.setData({
      'search.userName': '',
      'search.status': null,
      'search.orderType': null
    });
    this.fetchData();
  },

  handleCellClick(e) {
    const order = e.currentTarget.dataset.order;
    this.setData({ selectedOrder: order });
  },

  getOrderList() {
    this.setData({ loading: true });

    try {
      new Promise(resolve => setTimeout(resolve, 300));

      app.request({
        url: '/admin/order/getOrderList',
        method: 'GET',
        success: (res) => {
          if (res.code === 1) {
            const orderList = res.data.orderList || [];
            const orderState = res.data.orderState || [];
            this.setData({
              orderList,
              orderState,
              total: res.data.total
            });

            this.applyFilters(orderList);
          } else {
            wx.showToast({ title: res.msg || '获取记录失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('获取记录失败:', err);
          wx.showToast({ title: '获取记录失败', icon: 'none' });
        },
        complete: () => {
          this.setData({ loading: false });
        }
      });
    } catch (error) {
      console.error(error);
      this.setData({ loading: false });
      wx.showToast({ title: '加载出错', icon: 'none' });
    }
  },

  applyFilters(originalList) {
    let list = [...originalList];

    // 用户昵称模糊搜索
    if (this.data.search.userName) {
      const keyword = this.data.search.userName.toLowerCase();
      list = list.filter(order =>
        order.userName && order.userName.toLowerCase().includes(keyword)
      );
    }

    // 状态筛选
    if (this.data.search.status !== null && this.data.search.status !== '') {
      const status = parseInt(this.data.search.status);
      list = list.filter(order => order.currentStatus == status);
    }

    // 记录类型筛选
    if (this.data.search.orderType !== null && this.data.search.orderType !== '') {
      const orderType = this.data.search.orderType == 0 ? 'NORMAL' : 'PREMIUM';
      list = list.filter(order => order.orderType == orderType);
    }

    this.setData({ displayedOrders: list });
  },

  setupAutoRefresh() {
    this.refreshInterval = setInterval(() => {
      if (app.globalData.user && app.globalData.user.active) {
        this.fetchData();
      }
    }, 4000);
  },

  goHome() {
    wx.redirectTo({
      url: '/pages/admin/AdminHomeView/AdminHomeView'
    });
  },
  onChangeStatus(e) {
    const status = e.detail.value;
    this.setData({
      'search.status': status
    });
  },
  
  onChangeOrderType(e) {
    const orderType = e.detail.value;
    this.setData({
      'search.orderType': orderType
    });
  },
  onInputUserName(e) {
    const userName = e.detail.value;
    this.setData({
      'search.userName': userName
    }, () => {
      this.applyFilters(this.data.orderList);
    });
  },
  // 显示评论弹窗
  showCommentDialog(e) {
    const order = e.currentTarget.dataset.order;
    this.setData({
      selectedOrder: order,
      commentDialogVisible: true
    });
  },

  // 显示状态历史弹窗
  showStatusHistoryDialog(e) {
    const order = e.currentTarget.dataset.order;
    this.setData({
      selectedOrder: order,
      statusHistoryDialogVisible: true
    });
  },

  // 关闭所有弹窗
  closeDialogs() {
    this.setData({
      commentDialogVisible: false,
      statusHistoryDialogVisible: false,
      newCommentContent: '',
      selectedOrder: null
    });
  },

  // 输入评论内容
  onInputComment(e) {
    this.setData({ newCommentContent: e.detail.value });
  },

  // 提交新评论
  submitComment() {
    const { selectedOrder, newCommentContent } = this.data;
    if (!newCommentContent.trim()) {
      wx.showToast({ title: '请输入评论内容', icon: 'none' });
      return;
    }
  
    const orderId = selectedOrder.id;
  
    app.request({
      url: '/admin/order/saveOrUpdateComment',
      method: 'PUT',
      data: {
        orderId,
        content: newCommentContent
      },
      success: (res) => {
        if (res.code === 1) {
          wx.showToast({ title: '评论成功' });
  
          // ✅ 假设接口返回了新增的评论对象
          const newComment = res.data || {
            id: Date.now(), // 模拟 ID
            adminName: app.globalData.user?.nickName || '未知管理员',
            content: newCommentContent,
            createdAt: new Date().toLocaleString(),
            delete: true // 允许自己删除
          };
  
          // ✅ 更新 selectedOrder 的 commentList
          const updatedOrder = {
            ...selectedOrder,
            commentList: [
              ...(selectedOrder.commentList || []),
              newComment
            ]
          };
  
          // ✅ 更新 displayedOrders 中对应的记录
          const updatedDisplayedOrders = this.data.displayedOrders.map(order =>
            order.id === updatedOrder.id ? updatedOrder : order
          );
  
          // ✅ 更新 orderList（如果需要）
          const updatedOrderList = this.data.orderList.map(order =>
            order.id === updatedOrder.id ? updatedOrder : order
          );
  
          // ✅ 更新数据层
          this.setData({
            selectedOrder: updatedOrder,
            displayedOrders: updatedDisplayedOrders,
            orderList: updatedOrderList,
            newCommentContent: '' // 清空输入框
          });
  
        } else {
          wx.showToast({ title: res.msg || '评论失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('评论失败:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 删除评论
  deleteComment(e) {
    const commentId = e.currentTarget.dataset.id;
    const { selectedOrder } = this.data;
  
    // 找到要删除的评论对象
    const comment = selectedOrder.commentList.find(item => item.id === commentId);
  
    if (!comment) {
      wx.showToast({ title: '评论不存在', icon: 'none' });
      return;
    }
  
    // 再次校验权限
    const canDelete = comment.delete || (app.globalData.user && app.globalData.user.nickName === comment.adminName);
    if (!canDelete) {
      wx.showToast({ title: '无权删除此评论', icon: 'none' });
      return;
    }
  
    wx.showModal({
      title: '提示',
      content: '确定要删除该评论吗？',
      success: (res) => {
        if (res.confirm) {
          app.request({
            url: `/admin/order/deleteComment/${commentId}`,
            method: 'DELETE',
            success: (res) => {
              if (res.code === 1) {
                wx.showToast({ title: '删除成功' });
                this.fetchData(); // 重新加载记录数据
              } else {
                wx.showToast({ title: res.msg || '删除失败', icon: 'none' });
              }
            },
            fail: (err) => {
              console.error('删除失败:', err);
              wx.showToast({ title: '网络错误', icon: 'none' });
            }
          });
        }
      }
    });
  },
  //此方法只用于阻止冒泡或绑定方法，只写 catchtap 会报警告，所以绑定一个空方法
  void(){}
});